import os
import urllib.request
import argparse

FILE_CURR_PATH = os.path.dirname(__file__)

base_url = "https://repo.openeuler.org/openEuler-22.03-LTS-SP3/embedded_img/"

download_dir = os.path.join(FILE_CURR_PATH, "download_image")

link_list = []

find_link_str = '<tr><td colspan="2" class="link"><a'

parser = argparse.ArgumentParser(description="generate download image script")
parser.add_argument('-u', '--url', type=str, help="download url")
parser.add_argument('-d', '--dir_name', type=str, help="download dir name")

args = parser.parse_args()

if args.url :
    base_url = args.url
if args.dir_name :
    download_dir = os.path.join(FILE_CURR_PATH, args.dir_name)

run_cmd = []

def get_link_from_url(url:str, base_dir:str):
    global run_cmd
    print(f"# url: {url}")
    request = urllib.request.Request(url)
    response = urllib.request.urlopen(request)
    all_line = response.read().decode("utf-8").split("\n")

    for one_line in all_line:
        if one_line.find(find_link_str) < 0:
            continue
        begin_str = 'href="'
        end_str = '"'
        begin_num = one_line.find(begin_str) + len(begin_str)
        end_num = one_line.find(end_str, begin_num)
        get_str = one_line[begin_num:end_num]
        if (get_str == "../"):
            continue
        if get_str[-1] == "/":
            tmp_dir = os.path.join(base_dir, get_str)
            # print(f"mkdir -p {tmp_dir}")
            get_link_from_url(f"{url}{get_str}", tmp_dir)
            continue
        if os.path.splitext(get_str)[1] == ".sha256sum":
            continue
        run_cmd.append(f"mkdir -p {base_dir} && wget --no-check-certificate {url}{get_str} -P {base_dir}")

get_link_from_url(base_url, download_dir)

download_ext = [".sh", ".iso", ".rpi-sdimg", ".gz", ".tar", ".xz", ".ext4", ".img"]
download_name = ["zImage", "bzImage", "kernel-pi"]

for one_cmd in run_cmd:
    tmp_cmd_list = one_cmd.split(" ")
    tmp_split_url = os.path.splitext(tmp_cmd_list[6])
    bin_name = os.path.basename(tmp_split_url[0])
    if tmp_split_url[1] in download_ext:
        if tmp_split_url[1] == ".iso" and one_cmd.find("x86-64") < 0:
            continue
        if tmp_split_url[1] == ".gz" and os.path.splitext(tmp_split_url[0])[1] != ".cpio":
            continue
        print(one_cmd)
        continue
    if bin_name in download_name:
        print(one_cmd)
        continue

